﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System.Threading;
using System.Linq;
using UniRx;

public abstract class SkillBase
{
    /// <summary>
    /// 实体引用
    /// </summary>
    public UnitEntityBase entity { get; private set; }
    public void SetEntity(UnitEntityBase entity)
    {
        this.entity = entity;
    }

    /// <summary>
    /// 技能配置（读取后不改变的数据）
    /// </summary>
    public SkillConfig config { get; private set; }
    public void SetConfig(SkillConfig config)
    {
        this.config = config;
    }

    /// <summary>
    /// 技能数据（运行时会改变的数据）
    /// </summary>
    public SkillData data { get; private set; } = new SkillData();

    /// <summary>
    /// 当前等级的技能参数
    /// </summary>
    public List<double> upgradableParameters => config.upgradableParameters.Count <= 0 ? null : config.upgradableParameters[Mathf.Clamp(data.level - 1, 0, config.upgradableParameters.Count - 1)];

    /// <summary>
    /// 技能判定范围
    /// </summary>
    public SkillArea.Base area => m_Area ?? (m_Area = CreateArea());
    protected virtual SkillArea.Base CreateArea() => default;
    private SkillArea.Base m_Area;

    /// <summary>
    /// 效果池
    /// </summary>
    public ObjectPool<SkillEffectBase> effectPool { get; private set; }

    /// <summary>
    /// 中断token
    /// </summary>
    public CancellationTokenSource tokenSournce { get; private set; } = new CancellationTokenSource();



    protected virtual void OnInit() { }
    public async void Init()
    {
        var prefab = await entity.skillManager.GetEffectPrefab(config.assetName);
        effectPool = new ObjectPool<SkillEffectBase>(prefab);
        SceneManager.onLoadingMaskEnabled.Subscribe(_ => effectPool.Clear()).AddTo(entity);
        OnInit();
    }


    protected virtual UniTask OnExecute() => UniTask.CompletedTask;
    public UniTask Execute()
    {
        return OnExecute();
    }


    public virtual void OnReset() { }
    public void Reset()
    {
        data.Reset();
        OnReset();
    }


    /// <summary>
    /// 打断技能
    /// </summary>
    public void Shutdown()
    {
        tokenSournce.Cancel();
        tokenSournce.Dispose();
        tokenSournce = new CancellationTokenSource();
    }
}